package com.xiaomazi.edu.service.impl;

import cn.hutool.core.util.StrUtil;
import com.xiaomazi.common.utils.R;
import com.xiaomazi.edu.client.VideoClient;
import com.xiaomazi.edu.service.VideoService;
import com.xiaomazi.servicebase.exception.LLXYException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaomazi.edu.mapper.VideoMapper;
import com.xiaomazi.edu.entity.Video;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    @Autowired
    private VideoClient videoClient;

    /**
     * 根据小节id删除小节 包括视频
     * @param id 小节id
     * @return ok
     */
    @Override
    public R deleteVideoById(String id) {
        Video video = this.getById(id);
        String videoSourceId = video.getVideoSourceId();

        if (StrUtil.isNotBlank(videoSourceId)){
            R r = videoClient.removeAlyVideo(videoSourceId);
            if (!r.getSuccess()){
                throw new LLXYException(20001,"删除视频失败，熔断器");
            }
        }

        this.removeById(id);

        return R.ok();
    }

    /**
     * 根据课程Id删除所有小节和视频
     * @param courseId 课程id
     */
    @Override
    public void deleteVideoByCourseId(String courseId) {
        List<Video> videos = this.query().eq("course_id", courseId).list();
        if (null != videos && !videos.isEmpty()){
            List<String> videoIds = videos.stream().map(Video::getId).collect(Collectors.toList());
            List<String> videoSourceIds = videos.stream().map(Video::getVideoSourceId).collect(Collectors.toList());
            videoClient.deleteBatch(videoSourceIds);
            this.removeBatchByIds(videoIds);
        }
    }
}
